package com.opentool.dns;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.dns.*;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class DnsProxyHandler extends SimpleChannelInboundHandler<DatagramDnsResponse> {

    private  DnsProxy dnsProxy;

    private Channel clientChannel;

    public DnsProxyHandler(DnsProxy dnsProxy, Channel clientChannel){
        this.dnsProxy=dnsProxy;
        this.clientChannel=clientChannel;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, DatagramDnsResponse response) throws Exception{
        if(this.clientChannel!=null){
            response.retain();
            DatagramDnsResponse newResponse = new DatagramDnsResponse(dnsProxy.getClientRecipient(),dnsProxy.getClientSender(), response.id());

            for(int i=0;i<response.count(DnsSection.QUESTION);i++){
                try{
                    DnsRecord dnsRecord=response.recordAt(DnsSection.QUESTION,i);
                    newResponse.addRecord(DnsSection.QUESTION,dnsRecord);
                }catch (Exception e){
                    break;
                }
            }
            for(int i=0;i<response.count(DnsSection.ANSWER);i++){
                try{
                    DnsRecord dnsRecord=response.recordAt(DnsSection.ANSWER,i);
                    newResponse.addRecord(DnsSection.ANSWER,dnsRecord);
                }catch (Exception e){
                    break;
                }
            }
            for(int i=0;i<response.count(DnsSection.AUTHORITY);i++){
                try{
                    DnsRecord dnsRecord=response.recordAt(DnsSection.AUTHORITY,i);
                    newResponse.addRecord(DnsSection.AUTHORITY,dnsRecord);
                }catch (Exception e){
                    break;
                }
            }
            this.clientChannel.writeAndFlush(newResponse);
        }
    }
}
